package com.baidu.infinity.ui.fragment.home.shape.shapes

import android.graphics.Canvas
import android.graphics.Paint
import android.os.Build
import androidx.annotation.RequiresApi
import com.baidu.infinity.ui.fragment.home.shape.BaseShape
import com.baidu.infinity.ui.fragment.home.shape.LayerManager
import com.baidu.infinity.ui.util.state.ShapeState

class TextShape: BaseShape() {
    private val textLines = ArrayList<String>()
    private val mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        strokeWidth = 1f
        textSize = 25f
    }
    var mTextPaintColor: Int ?= null
    lateinit var fontMetrics: Paint.FontMetrics
    private var cy = 0f
    private var lineHeight = 0f
    @RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
    override fun setStartPoint(startX: Float, startY: Float) {
        super.setStartPoint(startX, startY)
        fontMetrics = mTextPaint.fontMetrics
        lineHeight = fontMetrics.bottom - fontMetrics.top
        cy = lineHeight
        endX = startX + 1
        endY = startY + 1
        rectF.left = Math.min(startX,endX)
        rectF.right = Math.max(startX,endX)
        rectF.top = Math.min(startY,endY)
        rectF.bottom = Math.max(startY,endY)
    }

    override fun setEndPoint(endX: Float, endY: Float) {
        super.setEndPoint(endX, endY)


    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        if(mState == ShapeState.DRAWING){
            canvas.drawRect(rectF,mOutLinePaint)
        }
        if(mTextPaintColor == null){
            mTextPaint.color = LayerManager.instance.mColor
        }
        textLines.forEach { text ->
            canvas.drawText(text,rectF.left,rectF.top + cy * (textLines.indexOf(text) + 1)- fontMetrics.bottom,mTextPaint)
        }
        rectF.bottom = rectF.top + cy * textLines.size
    }

    override fun containsPoint(x: Float, y: Float): Boolean {
        return rectF.contains(x,y)
    }
    fun setText(text: String){
        textLines.clear()
        textLines.addAll(text.split("\n"))
        rectF.right = rectF.left + mTextPaint.measureText(textLines[0])
        for (i in textLines){
            rectF.right = Math.max(rectF.right,rectF.left + mTextPaint.measureText(i))
        }
    }

}